//
//  CommunityViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/8/19.
//

import UIKit

class CommunityViewController: UIViewController {
    let viewModel = CommunityViewModel()
    let disposeBag = DisposeBag()
    private lazy var collectionView: UICollectionView = {
        let layout = WaterFallFlowLayout()
        layout.delegate = self
        layout.sectionInset = UIEdgeInsets(top: 16, left: 14, bottom: 30, right: 14)
        // 设置每行的项目数量
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
//        collectionView.register(cellWithClass: CommunityItemCell.self)
        collectionView.backgroundColor = UIColor.clear // 设置背景颜色
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.emptyDataSetSource = self
        collectionView.emptyDataSetDelegate = self
        return collectionView
    }()
     
    private lazy var releaseBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_home_release")
        button.titleForNormal = "发表"
        button.backgroundColor = UIColor(hexString: "#000000", transparency: 0.7)
        button.allRound(30)
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 10)
        return button
    }()
    
    private lazy var createBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_home_create")
        button.titleForNormal = "创作"
        button.backgroundColor = UIColor(hexString: "#000000", transparency: 0.7)
        button.allRound(30)
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 10)
        return button
    }()

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        releaseBtn.locationAdjust(buttonModel: .Top, spacing: 0)
        createBtn.locationAdjust(buttonModel: .Top, spacing: 0)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        self.viewModel.getDataList()
        self.view.addSubview(collectionView)
        self.view.addSubview(releaseBtn)
        self.view.addSubview(createBtn)
        
        self.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        createBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-30)
            make.width.height.equalTo(60)
            make.trailing.equalToSuperview().offset(-15)
        }
        
        releaseBtn.snp.makeConstraints { make in
            make.bottom.equalTo(createBtn.snp.top).offset(-22)
            make.width.height.equalTo(60)
            make.trailing.equalToSuperview().offset(-15)
        }
        
        self.collectionView.addHeaderRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page = 1
            self.viewModel.getDataList()
        }
        self.collectionView.addFooterRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page += 1
            self.viewModel.getDataList()
        }
        self.bindEvent()
        
        createBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.tabBarController?.selectedIndex = 2
        }
        
        releaseBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            if Appearance.shared.isLoign {
                self.navigationController?.pushViewController(WorksPageViewController())
            }else {
                GlobalRx.loginSubject.onNext(())
            }
        }
    }
    
    func initUI(){
        self.navigationItem.title = "社区"
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "icon_home_left"), for: .normal)
        leftBtn.titleForNormal = "你的AI"
        leftBtn.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        leftBtn.layoutButtonWithEdgeInsetsStyle(.Left, space: 6)
        let leftItem = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = leftItem
        
       
       
    }
    func videoGuide(proportion:String){
        let videoGuideView = CommunityGuideView()
        let width = (SCREEN_WIDTH - 38) / 2
        let height = calculateHeight(width: width, proportion: proportion)!
        videoGuideView.initUI(rect: CGRect(x: 15, y: 15, width: width, height: height + 68.0))
        Appearance.addViewToWindow(videoGuideView)
        videoGuideView.nextGuideBag = { [weak self] in }
    }
  
    func bindEvent(){
        self.viewModel.reloadDataSubject.subscribe(onNext: { [weak self] in
            self?.collectionView.endHeaderRefresh()
            self?.collectionView.endFooterRefresh()
            self?.collectionView.reloadData()
            guard let self = self else { return }
            if self.viewModel.dataArr.count > 0 {
                let userDefaults = UserDefaults.standard
//                userDefaults.set(false, forKey: firstLaunchCommunityGuideKey)
                if userDefaults.bool(forKey: firstLaunchCommunityGuideKey) == false {
                    userDefaults.set(true, forKey: firstLaunchCommunityGuideKey)
                    if let model = self.viewModel.dataArr.first {
                        self.videoGuide(proportion: model.proportion_value ?? "1:1")
                    }
                }
            }
        }).disposed(by: disposeBag)
        
        self.viewModel.likeSubject.subscribe(onNext: {[weak self] _ in
            self?.collectionView.endHeaderRefresh()
            self?.collectionView.endFooterRefresh()
            self?.collectionView.reloadData()
        }).disposed(by: disposeBag)
        
        GlobalRx.updateHomeData.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] id in
            if let index = self?.viewModel.dataArr.firstIndex(where: { $0.id == id}) {
                self?.viewModel.dataArr[index].is_like = self?.viewModel.dataArr[index].is_like == 0 ? 1 : 0
                self?.collectionView.reloadData()
            }
        }).disposed(by: disposeBag)
    }
    
    
     
}
extension CommunityViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WaterFallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.viewModel.dataArr[indexPath.item]
        let identifier = "\(indexPath.section)\(indexPath.row)"
        collectionView.register(CommunityItemCell.self, forCellWithReuseIdentifier: identifier)
        let cell:CommunityItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CommunityItemCell
        cell.setup(model)
        cell.likeBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.viewModel.clickLike(model: model)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.viewModel.dataArr[indexPath.item]
        if model.type == 1 {
            let vc = PaintingDetailsViewController()
            vc.homeModel = model
            self.navigationController?.pushViewController(vc)
        }else if model.type == 2 {
            let vc = VideoGeneratingVC()
            vc.homeModel = model
            self.navigationController?.pushViewController(vc)
        }else {
            let vc = CommunityMusicDetailsVC()
            vc.model = model
            self.navigationController?.pushViewController(vc)
        }
    }
    
    
    func waterFlowLayout(_ waterFlowLayout: WaterFallFlowLayout, itemHeight indexPath: IndexPath) -> CGFloat {
        let model = self.viewModel.dataArr[indexPath.item]
        if let p = model.proportion_value { // "9:16"
            let width = (SCREEN_WIDTH - 38) / 2
            let height = calculateHeight(width: width, proportion: p) ?? CGFloat(arc4random_uniform(150) + 50)
            return height + 68.0
        }
        return CGFloat(arc4random_uniform(200) + 68)
    }
    
    // 示例方法
    func calculateHeight(width: CGFloat, proportion: String) -> CGFloat? {
        // 分割比例字符串，获取宽度和高度的比率
        let components = proportion.split(separator: ":")
        guard components.count == 2,
              let widthRatio = Double(components[0]),
              let heightRatio = Double(components[1]) else {
            return nil
        }

        // 根据比例计算高度
        let height = width * CGFloat(heightRatio / widthRatio)
        return height
    }
}
extension CommunityViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    open func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        UIImage(named: "icon_nodata")
    }
    
    open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "暂无数据～"
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.pingFangSCRegular(ofSize: 15), .foregroundColor: Theme.color.text_d3]
        return NSAttributedString(string: text, attributes: attributes)
    }
    
    func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) {
        self.viewModel.getDataList()
    }
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return -navHig()
    }
}
